/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cronus.server;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import com.fdsapi.*;
import com.jamonapi.*;

/**
 *
 * @author Jannick
 */
public class SocketConnection {
    //Attributen
    private ServerSocket serversocket;
    private int port = 4444;
    private Main main;
    private boolean loop = true;
    //Constructor
    public SocketConnection( Main main ){
        this.main = main;
        try {
            serversocket = new ServerSocket(port);
            main.getMainScreen().addToLog("New connection made");
        } catch (IOException ex) {
            ex.printStackTrace();
            main.getMainScreen().addToLog("Can't make new connection.");
        }  
    }
    //Methodes
    public void handleConnection(){
        main.getMainScreen().addToLog("Waiting for client connection");
        //Loopje om alle connecties die worden gestart door de client te accepteren.
        while (loop == true){
            try {
                Socket socket = serversocket.accept();
                
                // Multithreading
                new ConnectionHandler( main, socket);
            }
            catch(BindException ex){
                System.out.println("Socket is al in gebruik, sluit andere Server sessie.");
                ex.printStackTrace();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public void stopConnection(){
        loop = false;
        main.getMainScreen().addToLog("Connection service stopped");
    }
    
    public void startConnection(){
        loop = true;
        main.getMainScreen().addToLog("Connection service started");
    }
}

class ConnectionHandler extends com.fdsapi.ResultSetUtils implements Runnable {
    //Attributen
    private Socket socket;
    private Main main;
    private ResultSet result;
    private ResultSet columnresult;
    private File temp = new File("C:\\temp.log");
    private File number = new File ("C:\\number.log");


    //Constructor
    public ConnectionHandler( Main main, Socket socket){
        this.main = main;
        this.socket = socket;
        // Start nieuwe thread
        Thread t = new Thread(this);
        t.start();
        
        //Tijdelijk bestand verwijderen
        try
        {
            
            if(temp.exists())
            {
                temp.delete();
            }
            else
            {
                temp.createNewFile();
            }
           
        }
        catch(Exception e){
            e.printStackTrace();
        }
        
        try
        {
            
            if(number.exists())
            {
                number.delete();
            }
            else
            {
                number.createNewFile();
            }
           
        }
        catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    //Methodes
    public void run(){
        try {
            
            //lees een Query van client
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String query = (String) ois.readObject();
            main.getMainScreen().addToLog("Query Received:" + query );
            
            //Voer de query uit op database en maak een arraylist d.m.v. methode Results2Array
            result = main.getSqlConnection().executeSelectQuery(query);
            Object[][] resultsarray = resultSetToObjectArray(result);
            
            //Haal resultset op en het aantal kolommen
            columnresult = main.getSqlConnection().executeSelectQuery("SELECT *"
                    + "FROM [CRONUS Nederland BV$Customer]");
            
            ResultSetMetaData rsmd = columnresult.getMetaData();
            int numcolumns = rsmd.getColumnCount();
            String[] columnName = new String[numcolumns];
            
            //Haal de kolomnamen op d.m.v. een for loop
            for (int i = 1; i < numcolumns+1; i++)
            {
                int k = i - 1;
                columnName[k] = rsmd.getColumnName(i);
            }
            
            if ( resultsarray != null ){
                //Stuur het resultaat terug
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                oos.writeObject(resultsarray);
                main.getMainScreen().addToLog("Result send:" + result );
                oos.close();
            }
            
            if(columnName != null)
            {
                OutputStream fos = new FileOutputStream(temp);
                OutputStream nfos = new FileOutputStream(number);
                PrintStream ps = new PrintStream(fos);
                PrintStream nps = new PrintStream(nfos);
                
                nps.print(numcolumns);
                for(String str : columnName)
                {
                    ps.println(str);
                }
                nps.close();
                ps.close();
            }
            
            ois.close();
            //oos.close();
            socket.close();
            main.getMainScreen().addToLog("Waiting for new query from client");
        } catch (IOException ex){
            ex.printStackTrace();
        } catch (ClassNotFoundException ex){
            ex.printStackTrace();
        } catch(SQLException ex){
            ex.printStackTrace();
        }
        
        
    }
    
    public String getColumnNames()
    {
        String columnName = null;
        try
        {
            //Haal resultset op en het aantal kolommen
            columnresult = main.getSqlConnection().executeSelectQuery("SELECT *"
                    + "FROM [CRONUS Nederland BV$Customer]");
            ResultSetMetaData rsmd = columnresult.getMetaData();
            int numcolumns = rsmd.getColumnCount();
            
            
            //Haal de kolom namen op d.m.v. een for loop
            for (int i = 1; i < numcolumns+1; i++)
            {
                columnName = rsmd.getColumnName(i);
            }
            
            System.out.println(columnName);
        }
        
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return columnName;
    }
}
